<?php

namespace app\controller;

use ali\Sms;
use app\BaseController;
use app\model\Account;
use app\model\Admin;
use think\facade\Cache;
use think\helper\Str;
use think\response\Json;

class Authorization extends BaseController
{
    public function adminLogin(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $data = $this->request->post();
            //校验验证码
            if (!captcha_check($data['captcha'])) throw new \Exception("验证码错误", 7002);
            $admin = $this->app->make(Admin::class)->where(['account' => $data['username'], 'state' => 1])->hidden(['create_time', 'update_time'])->find();

            if (!$admin) throw new \Exception("账号不存在", 7003);
            if (!checkPassword($data['password'], $admin->descode, $admin->password)) throw new \Exception("密码错误", 7004);
            $admin->login_token = Str::random(32);
            $admin->verify_time = date("Y-m-d H:i:s", strtotime("+7 hours"));
            $admin->save();
            $admin->hidden(['password', 'descode']);
            return $this->success(['id' => $admin->id, 'login_token' => $admin->login_token, 'verify_time' => $admin->verify_time]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function checkAdminLogin(): Json
    {
        try {
            $auth = getAuthorization();
            $admin = $this->app->make(Admin::class)->where(['id' => $auth['id'], 'state' => 1, 'login_token' => $auth['login_token']])->find();
            if (empty($admin)) throw new \Exception("登录已过期", 7004);
            $timer = strtotime($admin->verify_time);
            if ($timer < time()) throw new \Exception("登录已过期", 7004);
            return $this->success($admin);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function merchantLoginCode(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
//            if (!captcha_check($this->request->post('code'))) throw new \Exception("图形验证码错误", 7002);
            //查询是否有该手机号
            $data = $this->app->make(Account::class)->phoneDetail();
            //校验今日获取登录验证码次数
            $todayTimes = Cache::get("login_code_timer_" . $data->mobile, 1);
            if ($todayTimes > 5) throw new \Exception("今日获取登录验证码次数过多", 7005);
            $lockTimer = Cache::get("login_code_lock_" . $data->mobile);
            if ($lockTimer) throw new \Exception("获取登录验证码过于频繁", 7006);
            //缓存验证码
            $lastTime = strtotime(date("Y-m-d 23:59:59"));
            $ttl = $lastTime - time();
            if ($this->request->ip() != '127.0.0.1') {
                $code = Str::random(6, 1);//验证码
//            $send = Sms::sendSms($data->mobile, compact("code"), 'SMS_474460088');
                $send = sendSms("191585", $data->mobile, compact("code"));
                if (empty($send)) throw new \Exception("短信发送失败", 7002);
            } else {
                $code = 123456;
            }

            Cache::set("login_code_" . $data->mobile, $code, 300);
            Cache::set("login_code_timer_" . $data->mobile, $todayTimes + 1, $ttl);
            Cache::set("login_code_lock_" . $data->mobile, 1, 60);
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function merchantLogin(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $data = $this->app->make(Account::class)->phoneDetail();
            $password = $this->request->post("code");
            if (!checkPassword($password, $data->decode, $data->password)) throw new \Exception("密码错误", 7002);
            $data->token = Str::random(32);
            $data->last_time = date("Y-m-d H:i:s", strtotime("+7 day"));//存储7天
            $data->save();
            return $this->success(['id' => $data->id, 'token' => $data->token, 'last_time' => $data->last_time]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function checkMerchantLogin(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $author = getAuthorization();
            $data = $this->app->make(Account::class)->with(['store', 'supplier' => function ($query) {
                $query->with(['appid']);
            }])->where(['id' => $author['id'], 'token' => $author['token'], 'state&is_del' => 1])->find();
            if (empty($data)) throw new \Exception("登录已过期", 7004);
            $time = strtotime($data->last_time);
            if ($time < time()) throw new \Exception("登录已过期", 7004);
            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function modifyPassword(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $auth = getAuthorization();
            $param = $this->request->post();
            $data = $this->app->make(Admin::class)->where(['id' => $auth['id'], 'state' => 1, 'login_token' => $auth['login_token']])->find();
            if (empty($data)) throw new \Exception("账号不存在或已注销", 7004);
            $timer = strtotime($data->verify_time);
            if ($timer < time()) throw new \Exception("登录已过期", 7004);
            if (!checkPassword($param['oldPassword'], $data->descode, $data->password)) throw new \Exception("旧密码错误", 7004);
            if ($param['newPassword'] != $param['confirmPassword']) throw new \Exception("两次输入密码不一致", 7004);
            $password = setPassword($param['newPassword']);
            $data->password = $password['password'];
            $data->descode = $password['encode'];
            $data->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function modifyMerchantPassword(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $auth = getAuthorization();
            $param = $this->request->post();
            $data = $this->app->make(Account::class)->where(['id' => $auth['id'], 'state' => 1, 'token' => $auth['token']])->find();
            if (empty($data)) throw new \Exception("账号不存在或已注销", 7004);
            $timer = strtotime($data->last_time);
            if ($timer < time()) throw new \Exception("登录已过期", 7004);
            if (!checkPassword($param['oldPassword'], $data->decode, $data->password)) throw new \Exception("旧密码错误", 7004);
            if ($param['newPassword'] != $param['confirmPassword']) throw new \Exception("两次输入密码不一致", 7004);
            $password = setPassword($param['newPassword']);
            $data->password = $password['password'];
            $data->decode = $password['encode'];
            $data->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function merchantForgotPassword(): Json
    {
        try {
            if (!$this->request->isPost()) throw new \Exception("请求方式错误", 7001);
            $data = $this->app->make(Account::class)->phoneDetail();
            if (empty($data)) throw new \Exception("手机号不存在", 7002);
            $code = $this->request->post("code");
            if (empty(Cache::get('login_code_' . $data->mobile))) throw new \Exception("验证码已过期", 7002);
            if ($code != Cache::get('login_code_' . $data->mobile)) throw new \Exception("验证码错误", 7002);
            $password = setPassword($this->request->post("password"));
            $data->password = $password['password'];
            $data->decode = $password['encode'];
            $data->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }
}
